#include "tpthread.h"
#include "threadpool.h"
#include <thread>

bool exit_ = false;

void *
task(void *data, int id)
{
    PThread *t = (PThread *)data;
    do
    {
        srand(std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count());
        int count = rand() % 500;

        /* printf("thread: %d, msleep: %d\n", id, count); */
        std::this_thread::sleep_for(std::chrono::milliseconds(count));

        if (!t)
        {
            break;
        }

        if (!t->active())
        {
            break;
        }
    }
    while (true);

    return NULL;
}

void
launch_rand(void *data)
{
    ThreadPool *tpool = (ThreadPool *)data;

    while (!exit_)
    {
        srand(time(NULL));
        int N = rand() % 5 + 1;

        for (int i = 0; i < N; ++i)
        {

#if 0
            PThread t;
            t.setEntry(task, &t, i);
            t.start();
            t.stop();
#else
            PThread *t = new PThread();
            t->setEntry(task, NULL, i);
            t->start();
#endif
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
    }
}


const int N = 1000;

ThreadPool *tpool = NULL;
int main()
{
    tpool = new ThreadPool();

    std::thread t(launch_rand, tpool);

    getchar();
    exit_ = true;
    t.join();

    delete tpool;

    getchar();

    return 0;
}
